package com.yiboshi.rehrs.util;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

public class JSONBuilder {
    JSONObject json;

    private JSONBuilder() {
        this.json = new JSONObject();
    }

    public static JSONBuilder start() {
        return new JSONBuilder();
    }

    public static JSONBuilder start(String key, Object v) {
        return new JSONBuilder().put(key, v);
    }


    public JSONBuilder put(String key, Object v) {

        if (v == null || StringUtil.isEmpty(v.toString())) {
            return this;
        } else if (v instanceof JSONBuilder) {
            v = ((JSONBuilder) v).end();
        }
        if (json == null) {
            this.json = new JSONObject();
        }
        json.put(key, v);
        return this;
    }

    public <T> T get(String key) {
        return (T) json.get(key);
    }

    public JSONObject end() {
        return this.json;
    }

    public String toJSONString() {
        return end().toJSONString();
    }

    public <E> JSONBuilder putInArrayList(String name, E value) {
        if (value == null) {
            return this;
        }
        List<E> object = this.get(name);
        if (CollectionUtils.isEmpty(object)) {
            object = new ArrayList<>();
            put(name, object);
        }
        object.add(value);
        return this;
    }

    public boolean containsKey(Object key) {
        return json.containsKey(key);
    }
}
